using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace EventScavenger
{
    public partial class MachineLogFilter : Form
    {
        #region Constructors
        public MachineLogFilter()
        {
            InitializeComponent();
        } 
        #endregion

        #region Properties
        private List<MachineLogEntry> selectedMachineLogs = new List<MachineLogEntry>();
        public List<MachineLogEntry> SelectedMachineLogs
        {
            get { return selectedMachineLogs; }
            set { selectedMachineLogs = value; }
        }
        private bool allEnabled;
        public bool AllEnabled
        {
            get { return allEnabled; }
            set { allEnabled = value; }
        }
        private bool allowNone = false;
        public bool AllowNone
        {
            get { return allowNone; }
            set { allowNone = value; }
        }
        #endregion

        #region Private stuff
        private EventScavengerDAL sqlEventSource;
        private bool selfChecking = false;
        private void ShowLoadingMessage()
        {
            lvwEventMachineLogs.Items.Clear();
            lvwEventMachineLogs.Items.Add("Loading...");
            System.Windows.Forms.Application.DoEvents();
        }
        private List<MachineLogEntry> availableMachineLog;
        private void LoadListView()
        {
            ListViewItem lvwi;
            if (sqlEventSource.AvailableMachineLog == null)
            {
                LoadMachineLogEntries();
            }
            else if (sqlEventSource.AvailableMachineLog.Count == 0)
            {
                LoadMachineLogEntries();
            }
            else
            {
                availableMachineLog = sqlEventSource.AvailableMachineLog;
            }
            
            Cursor.Current = Cursors.WaitCursor;
            selfChecking = true;
            try
            {
                lvwEventMachineLogs.BeginUpdate();
                lvwEventMachineLogs.Items.Clear();
                List<ListViewItem> listViewBuffer = new List<ListViewItem>();
                lvwi = new ListViewItem("All");
                if (allEnabled)
                {
                    lvwi.Checked = true;
                }
                listViewBuffer.Add(lvwi);
                foreach (MachineLogEntry mle in availableMachineLog)
                {
                    lvwi = new ListViewItem(mle.Machine + "\\" + mle.LogName);
                    if (!mle.Enabled)
                    {
                        lvwi.ForeColor = Color.Gray;
                    }
                    lvwi.Checked = MachineLogInList(selectedMachineLogs,mle) || allEnabled;
                    lvwi.SubItems.Add(mle.LastPollTime.ToString("yyyy-MM-dd HH:mm"));
                    lvwi.SubItems.Add(mle.PollFrequency.ToString());
                    lvwi.Tag = mle;
                    listViewBuffer.Add(lvwi);
                }
                lvwEventMachineLogs.Items.AddRange(listViewBuffer.ToArray());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                lvwEventMachineLogs.EndUpdate();
            }
            Cursor.Current = Cursors.Default;
            selfChecking = false;
        }

        private bool MachineLogInList(List<MachineLogEntry> list, MachineLogEntry searchItem)
        {
            foreach (MachineLogEntry mle in list)
            {
                if (mle.Machine == searchItem.Machine && mle.LogName == searchItem.LogName)
                    //if (mle.Equals(searchItem))
                    return true;
            }
            return false;
        }
        private void LoadMachineLogEntries()
        {
            availableMachineLog = sqlEventSource.GetMachineLogList(Properties.Settings.Default.ViewDisabledLogs);
        }
        #endregion

        public DialogResult Show(EventScavengerDAL sqlEventSource)
        {
            this.sqlEventSource = sqlEventSource;
            return ShowDialog();
        }

        #region Form events
        private void MachineLogFilter_Load(object sender, EventArgs e)
        {
            if ((Properties.Settings.Default.MachineLogFilterLocation != null) && (!Properties.Settings.Default.MachineLogFilterLocation.Equals(new Point(0, 0))))
            {
                this.Location = Properties.Settings.Default.MachineLogFilterLocation;
            }
            if ((Properties.Settings.Default.MachineLogFilterSize != null) && (!Properties.Settings.Default.MachineLogFilterSize.Equals(new Size(0, 0))))
            {
                this.Size = Properties.Settings.Default.MachineLogFilterSize;
            }
            chkViewDisabled.Checked = Properties.Settings.Default.ViewDisabledLogs;

            //ensuring the previously selected item is visible again on startup
            new System.Threading.Thread(delegate()
                {
                    this.Invoke((MethodInvoker)delegate()
                        {
                            ShowLoadingMessage();
                            System.Threading.Thread.Sleep(500);
                            LoadListView();
                        }
                    );
                }
            ).Start();
        }
        private void MachineLogFilter_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                Properties.Settings.Default.MachineLogFilterLocation = this.Location;
                Properties.Settings.Default.MachineLogFilterSize = this.Size;
            }
            Properties.Settings.Default.Save();
        }
        private void MachineLogFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                Close();
        }
        #endregion

        #region List view events
        private void lvwEventMachineLogs_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            int selectedCount = 0;
            if (!selfChecking)
            {
                selfChecking = true;
                if (e.Item.Text == "All")
                {
                    foreach (ListViewItem lvwi in lvwEventMachineLogs.Items)
                    {
                        if (lvwi.Text != "All")
                        {
                            lvwi.Checked = e.Item.Checked;
                        }
                    }
                }
                else
                {
                    if (!e.Item.Checked)
                    {
                        lvwEventMachineLogs.Items[0].Checked = false;
                    }
                    else
                    {
                        bool testAll = true;
                        foreach (ListViewItem lvwi in lvwEventMachineLogs.Items)
                        {
                            if ((lvwi.Text != "All") && (!lvwi.Checked))
                            {
                                testAll = false;
                            }
                        }
                        lvwEventMachineLogs.Items[0].Checked = testAll;
                    }
                }
                selfChecking = false;
                foreach (ListViewItem lvwi in lvwEventMachineLogs.Items)
                {
                    if (lvwi.Checked)
                        selectedCount++;
                }
                cmdOK.Enabled = allowNone || (selectedCount > 0);
            }
        }
        #endregion

        #region Button events
        private void cmdOK_Click(object sender, EventArgs e)
        {
            selectedMachineLogs = new List<MachineLogEntry>();
            foreach (ListViewItem lvwi in lvwEventMachineLogs.Items)
            {
                if (lvwi.Text != "All")
                {
                    if (lvwi.Checked)
                        selectedMachineLogs.Add((MachineLogEntry)lvwi.Tag);
                }
                else
                    allEnabled = lvwi.Checked;
            }
            this.DialogResult = DialogResult.OK;
            Close();
        }
        private void cmdReload_Click(object sender, EventArgs e)
        {
            ShowLoadingMessage();
            LoadMachineLogEntries();
            LoadListView();
            cmdOK.Enabled = true;
        } 
        #endregion

        #region Checkbox events
        private void chkViewDisabled_CheckedChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.ViewDisabledLogs = chkViewDisabled.Checked;
            Properties.Settings.Default.Save();
            cmdReload_Click(sender, e);
        } 
        #endregion
    }
}